
package com.winning.sx.microframework.controller.busi;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.winning.dapi.data.entity.DataTable;
import com.winning.sx.microframework.common.util.Constains;
import com.winning.sx.microframework.common.util.FlowCodeUtil;
import com.winning.sx.microframework.common.util.SqlTool;
import com.winning.sx.microframework.model.exception.CustomException;
import com.winning.sx.microframework.model.manage.LoginSession;
import com.winning.sx.microframework.model.message.AjaxDataResponseMessage;
import com.winning.sx.microframework.model.message.AjaxTableResponseMessage;
import com.winning.sx.microframework.service.EasyService;
import com.winning.sx.microframework.service.base.EquipmentService;
import com.winning.sx.microframework.service.sysmanage.ConstService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/busi/equipmentGet")
public class EquipmentGetController {
    @Autowired
    EasyService easyService;
    @Autowired
    EquipmentService equipmentService;
    @Autowired
    ConstService service;

    @RequestMapping(value = {"/", ""})
    public ModelAndView init() throws IOException, CustomException, SQLException {
        ModelAndView mv = new ModelAndView("/busi/equipmentGet");
        List userType = service.queryCount("108");
        mv.addObject("userType", userType);
        LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
        Map<String, String> param = new HashMap();
        param.put("organizationType", "400001");
        param.put("superOrganizationId", login.getOrgId());//全部客户的都展示，并不是展示中心自己的下属机构
        mv.addObject("organizationName", JSON.toJSON(service.queryMyOrg(param)).toString());

        List staffList = easyService.querySql("select  *  from BASE_Staff   where  validFlag='100001' and organizationId in (" +
                " select id from BASE_Organization where organizationType='400001' " +
                ") ", new HashMap()).getDataRows();
        mv.addObject("staffList", staffList);

        Map eqRootClassP = new HashMap();
        eqRootClassP.put("superId", "0");
        eqRootClassP.put("validFlag", "100001");
        DataTable eqRootClassS = easyService.queryList("BASE_EqClass", eqRootClassP);
        List eqRootClass = eqRootClassS.getDataRows();
        mv.addObject("eqRootClass", eqRootClass);
        List brand = service.queryCount("300");
        mv.addObject("brand", brand);
        Map map = new HashMap();
        List eqClass = easyService.querySql("SELECT " +
                "  c1.name + '-' + c2.name name, " +
                "  c2.code " +
                "FROM BASE_EqClass c1 " +
                "  RIGHT JOIN BASE_EqClass c2 ON c1.id = c2.superId " +
                "WHERE c2.validFlag = '100001' AND c1.id IS NOT NULL ", map).getDataRows();
        mv.addObject("eqClass", eqClass);
        return mv;
    }

    @RequestMapping(value = {"/printGet/{id}"})
    public ModelAndView printGet(@PathVariable("id") String id) throws IOException, CustomException, SQLException {
        ModelAndView mv = new ModelAndView("/busi/printEquipmentGet");
        Map map = new HashMap();
        //获取主要数据
        Map mainData = easyService.querySql("select " +
                "d.*,getS.name getSName,useS.name useSName,useO.name useOName,checkS.name checkSName,checkO.name checkOName,c1.name stateName,c2.name useTypeName " +
                "from BUSI_EquipmentGet d " +
                "left join BASE_Staff getS on getS.id=d.getStaffId " +
                "left join base_staff useS on useS.id=d.useStaffId " +
                "left join BASE_Organization useO on useO.id=d.useOrgId " +
                "left join base_staff checkS on checkS.id=d.checkStaffId " +
                "left join BASE_Organization checkO on checkO.id=d.checkOrgId " +
                "left join BASE_Const c1 on c1.code=d.state " +
                "left join BASE_Const c2 on c2.code=d.useType" +
                " where d.id=" + id, map).getDataRows().get(0);

//        Map orgInfo = equipmentService.getOrgname(mainData.get("equipmentId").toString());

        List detailList = easyService.querySql("select " +
                "d.*,g.warehouseId,g.flowCode,e.name ,ec.name typeName,c1.name brandName,e.brand brandCode, e.type oneCode " +
//                ",(select sum(count) from BUSI_WarehouseChange c where c.getId=:getId and c.validFlag='100001' and c.modelId=d.modelId) changeCount" +
                " from BUSI_EquipmentGetDetail d " +
                "  LEFT JOIN  BUSI_EquipmentGet g on g.id=d.getId " +
                "  LEFT JOIN  BASE_EquipmentDetail e on d.modelId=e.id " +
                "  LEFT JOIN  BASE_EqClass ec on e.type=ec.code " +
                "  LEFT JOIN  BASE_Const c1 on e.brand=c1.code" +
                " where d.validFlag='100001' and d.getId=" + id, map).getDataRows();

        mv.addObject("mainData", mainData);
//        mv.addObject("orgInfo", orgInfo);
        mv.addObject("detailList", detailList);
        mv.addObject("printTime", SqlTool.getNowTimeString2());
        return mv;
    }

    @RequestMapping(value = {"/printChange/{id}/{changeIds}"})
    public ModelAndView printChange(@PathVariable("id") String id, @PathVariable("changeIds") String changeIds) throws IOException, CustomException, SQLException {
        ModelAndView mv = new ModelAndView("/busi/printWarehouseChange");
        Map map = new HashMap();
        //获取主要数据
        Map mainData = easyService.querySql("select " +
                "d.*,getS.name getSName,useS.name useSName,useO.name useOName,checkS.name checkSName,checkO.name checkOName,c1.name stateName,c2.name useTypeName " +
                "from BUSI_EquipmentGet d " +
                "left join BASE_Staff getS on getS.id=d.getStaffId " +
                "left join base_staff useS on useS.id=d.useStaffId " +
                "left join BASE_Organization useO on useO.id=d.useOrgId " +
                "left join base_staff checkS on checkS.id=d.checkStaffId " +
                "left join BASE_Organization checkO on checkO.id=d.checkOrgId " +
                "left join BASE_Const c1 on c1.code=d.state " +
                "left join BASE_Const c2 on c2.code=d.useType" +
                " where d.id=" + id, map).getDataRows().get(0);

//        Map orgInfo = equipmentService.getOrgname(mainData.get("equipmentId").toString());

        List detailList = easyService.querySql("select " +
                "d.*,g.warehouseId,g.flowCode,e.name ,ec.name typeName,c1.name brandName,e.brand brandCode, e.type oneCode " +
//                ",(select sum(count) from BUSI_WarehouseChange c where c.getId=:getId and c.validFlag='100001' and c.modelId=d.modelId) changeCount" +
                " from BUSI_EquipmentGetDetail d " +
                "  LEFT JOIN  BUSI_EquipmentGet g on g.id=d.getId " +
                "  LEFT JOIN  BASE_EquipmentDetail e on d.modelId=e.id " +
                "  LEFT JOIN  BASE_EqClass ec on e.type=ec.code " +
                "  LEFT JOIN  BASE_Const c1 on e.brand=c1.code" +
                " where d.validFlag='100001' and d.getId=" + id, map).getDataRows();

        List changeList = easyService.querySql("select " +
                "d.*,toW.organizationId oneOrganization2,ec.code oneCode,c1.code brandCode,e.id model,e.name,ec.name eqClassName,c1.name brandName,c2.name typeName,c3.name stateName,stC.name createStaffName,stU.name updateStaffName " +
                "from BUSI_WarehouseChange d " +
                "left join BASE_EquipmentDetail e on d.modelId=e.id " +
                "left join BASE_Const c1 on e.brand=c1.code " +
                "left join BASE_Const c2 on d.type=c2.code " +
                "left join BASE_Const c3 on d.state=c3.code " +
                "left join BASE_EqClass ec on e.type=ec.code " +
                "left join BASE_Staff stC on stC.id=d.createStaffId " +
                "left join BASE_Staff stU on stU.id=d.updateStaffId " +
                "left join BASE_Warehouse toW on toW.id=d.toWarehouseId " +
                "where d.validFlag='100001'  and d.id in (" + changeIds + ")", map).getDataRows();

        mv.addObject("mainData", mainData);
//        mv.addObject("orgInfo", orgInfo);
        mv.addObject("detailList", detailList);
        mv.addObject("changeList", changeList);
        mv.addObject("printTime", SqlTool.getNowTimeString2());
        return mv;
    }

    @ResponseBody
    @RequestMapping(value = {"/queryList"})
    public AjaxTableResponseMessage queryList(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            DataTable all = easyService.querySql("select " +
                            "d.*,getS.name getSName,useS.name useSName,useO.name useOName,checkS.name checkSName,checkO.name checkOName,c1.name stateName,c2.name useTypeName " +
                            "from BUSI_EquipmentGet d " +
                            "left join BASE_Staff getS on getS.id=d.getStaffId " +
                            "left join base_staff useS on useS.id=d.useStaffId " +
                            "left join BASE_Organization useO on useO.id=d.useOrgId " +
                            "left join base_staff checkS on checkS.id=d.checkStaffId " +
                            "left join BASE_Organization checkO on checkO.id=d.checkOrgId " +
                            "left join BASE_Const c1 on c1.code=d.state " +
                            "left join BASE_Const c2 on c2.code=d.useType" +
                            " where d.validFlag='100001' " +
                            (param.get("warehouseId") == null ? "" : (" and d.warehouseId in (" + param.get("warehouseId") + ")")) +
                            (param.get("b_createTime") != null ? (" and d.createTime>='" + param.get("b_createTime") + " 00:00:00'") : "") +
                            (param.get("e_createTime") != null ? (" and d.createTime<='" + param.get("e_createTime") + " 23:59:59'") : ""),
                    param);
            ajaxTableResponseMessage.setDatas(all.getDataRows());
            ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
            ajaxTableResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/queryDetailList"})
    public AjaxTableResponseMessage queryDetailList(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            DataTable all = easyService.querySql("select " +
                    "d.*,g.warehouseId,g.flowCode,e.name ,ec.name typeName,c1.name brandName,e.brand brandCode, e.type oneCode " +
                    ",(select sum(count) from BUSI_WarehouseChange c where c.getId=:getId and c.validFlag='100001' and c.modelId=d.modelId) changeCount" +
                    " from BUSI_EquipmentGetDetail d " +
                    "  LEFT JOIN  BUSI_EquipmentGet g on g.id=d.getId " +
                    "  LEFT JOIN  BASE_EquipmentDetail e on d.modelId=e.id " +
                    "  LEFT JOIN  BASE_EqClass ec on e.type=ec.code " +
                    "  LEFT JOIN  BASE_Const c1 on e.brand=c1.code" +
                    " where d.validFlag='100001' and d.getId=:getId", param);
            ajaxTableResponseMessage.setDatas(all.getDataRows());
            ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
            ajaxTableResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }


    @ResponseBody
    @RequestMapping(value = {"/save"})
    @Transactional(propagation = Propagation.REQUIRED)
    public AjaxDataResponseMessage insert(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
                map = objectMapper.readValue(datas, Map.class);
                Map param = new HashMap();
                param.put("id", map.get("id").toString());
                param.put("warehouseId", map.get("warehouseId").toString());
                param.put("getStaffId", map.get("getStaffId").toString());
                param.put("getStaffTel", map.get("getStaffTel").toString());
                param.put("useOrgId", map.get("useOrgId").toString());
                param.put("useStaffId", map.get("useStaffId").toString());
                param.put("useType", map.get("useType").toString());
                param.put("useTel", map.get("useTel").toString());
                param.put("usePosition", map.get("usePosition").toString());
                param.put("reason", map.get("reason").toString());
                param.put("flowCode", map.get("flowCode").toString().equals("") ? FlowCodeUtil.getFlowCode() : map.get("flowCode").toString());
                if (map.get("id") != null && !"".equals(map.get("id"))) {
                    param.put("createStaffId", login.getStaffId().toString());
                }
                param.put("state", Constains.EQUIPMENT_USE_STATE_NEW);
                easyService.save("BUSI_EquipmentGet", "id", param);
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ajaxDataResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/saveState"})
    @Transactional(propagation = Propagation.REQUIRED)
    public AjaxDataResponseMessage saveState(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
                map = objectMapper.readValue(datas, Map.class);
                Map param = new HashMap();
                param.put("id", map.get("id").toString());
                param.put("checkStaffId", map.get("checkStaffId").toString());
                param.put("checkOrgId", map.get("checkOrgId").toString());
                param.put("checkTime", map.get("checkTime").toString());
                param.put("state", Constains.EQUIPMENT_USE_STATE_CHECK_1);
                easyService.save("BUSI_EquipmentGet", "id", param);
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ajaxDataResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/saveList"})
    @Transactional(propagation = Propagation.REQUIRED)
    public AjaxDataResponseMessage saveList(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                Map param = new HashMap();
                param.put("id", map.get("id").toString());
                param.put("getId", map.get("getId").toString());
                param.put("modelId", map.get("modelId").toString());
                param.put("getCount", map.get("getCount").toString());
                param.put("tips", map.get("tips").toString());
                easyService.save("BUSI_EquipmentGetDetail", "id", param);
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ajaxDataResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/saveChangeInfo"})
    @Transactional(propagation = Propagation.REQUIRED)
    public AjaxDataResponseMessage saveChangeInfo(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
                map = objectMapper.readValue(datas, Map.class);
                Map param = new HashMap();
                param.put("modelId", map.get("modelId").toString());
                param.put("warehouseId", map.get("warehouseId").toString());
                param.put("getId", map.get("getId").toString());
                param.put("getDetailId", map.get("id").toString());
                param.put("count", map.get("count").toString());
                param.put("reason", map.get("tips").toString());
                param.put("flowCode", FlowCodeUtil.getFlowCode());
                param.put("state", Constains.WAREHOUSE_CHANGE_STATE_1);
                param.put("type", Constains.WAREHOUSE_CHANGE_TYPE_21);
                param.put("createStaffId", login.getStaffId().toString());
                easyService.save("BUSI_WarehouseChange", "id", param);
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ajaxDataResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/delete"})
    public AjaxDataResponseMessage delete(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                easyService.delete("BUSI_EquipmentGet", "id", map);
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("删除失败：" + e.getMessage());
        }
        return ajaxDataResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/deleteList"})
    public AjaxDataResponseMessage deleteList(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                easyService.delete("BUSI_EquipmentGetDetail", "id", map);
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("删除失败：" + e.getMessage());
        }
        return ajaxDataResponseMessage;
    }
}

